package com.jrzh.mvc.convert.sys;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.jrzh.common.exception.ProjectException;
import com.jrzh.common.tools.CollectionTools;
import com.jrzh.common.utils.PasswordUtils;
import com.jrzh.common.utils.ReflectUtils;
import com.jrzh.framework.base.convert.BaseConvertI;
import com.jrzh.framework.contants.GeneralConstant;
import com.jrzh.mvc.model.sys.RoleModel;
import com.jrzh.mvc.model.sys.UserModel;
import com.jrzh.mvc.view.sys.UserView;

@Component("userConvert")
public class UserConvert implements BaseConvertI<UserModel, UserView> {
	public UserModel addConvert(UserView view) throws ProjectException{
		UserModel model = new UserModel();
		ReflectUtils.copySameFieldToTarget(view, model);	
		model.setSalt(PasswordUtils.getSalt());
		model.setPassword(PasswordUtils.encryptPassword(GeneralConstant.DEFAULT_ADMIN_PASSWORD, model.getSalt()));
		model.setAuditPassword(PasswordUtils.encryptPassword(GeneralConstant.DEFAULT_ADMIN_PASSWORD, model.getSalt()));
		return model;
	}

	public UserModel editConvert(UserView view, UserModel model) throws ProjectException{
		model.setCode(view.getCode());
		model.setName(view.getName());
		model.setCardId(view.getCardId());
		model.setEmail(view.getEmail());
		model.setRemark(view.getRemark());
		model.setTel(view.getTel());
		model.setAddress(view.getAddress());
		model.setSex(view.getSex());
		model.setIsDisable(view.getIsDisable());
		model.setSortNum(view.getSortNum());
		return model;
	}

	public UserView convertToView(UserModel model) throws ProjectException{
		UserView view = new UserView();
		if(null != model){
			ReflectUtils.copySameFieldToTarget(model, view);
			view.setStrSex(model.getSex()==1?"男":"女");
		}
		List<RoleModel> roles = model.getRoles();
		String[] roleIds = CollectionTools.collect(roles, "id", new String[]{});
		String[] rolesName = CollectionTools.collect(roles, "name", new String[]{});
		view.setRoles(StringUtils.join(rolesName,","));
		view.setRoleIds(roleIds);
		return view;
	}

}
